<script setup>
import {useForm} from "@inertiajs/vue3";
import useDialog from '@/composables/useDialog'
import useLoading from '@/composables/useLoading'
import useRequest from '@/composables/useRequest'
import {Message} from "@arco-design/web-vue";

const {FormRef, visible, mode, pk, actionName, width} = useDialog()
const {loading, setLoading} = useLoading()

const {createApi, updateApi, showApi} = useRequest('admin.content.article.tags')

const emit = defineEmits(["success", "close"]);

const form = useForm({
    name: '',
    slug: '',
    color: '',
})

const rules = {
    name: [{required: true, message: '请输入标签名称', trigger: 'blur'}],
    slug: [{required: true, message: '请输入标签标识', trigger: 'blur'}],
}
const handleSubmit = async () => {
    try {
        setLoading(true)
        const res = await FormRef.value?.validate()
        if (res) return false
        const apiMethod = mode.value === 'edit'
            ? () => updateApi(pk.value, form)
            : () => createApi(form)
        await apiMethod()
        Message.success(`${actionName.value}成功`)
        emit('success')
    } catch (error) {
        return false
    } finally {
        setLoading(false)
    }
}

const handleClose = () => {
    FormRef.value?.resetFields()
    form.reset()
    emit('close')
}

// 打开弹窗
const add = async () => {
    mode.value = 'add'
    visible.value = true
}

const edit = async (id) => {
    try {
        setLoading(true)
        pk.value = id
        const {data} = await showApi(id)
        Object.assign(form, data)
        mode.value = 'edit'
        visible.value = true
    } finally {
        setLoading(false)
    }
}

defineExpose({add, edit})
</script>
<template>
    <a-drawer
        v-model:visible="visible"
        :loading="loading"
        :title="`${actionName}`"
        :width
        @close="handleClose"
        @before-ok="handleSubmit"
    >
        <a-spin :loading="loading" class="w-full">


            <a-form ref="FormRef" :model="form" :rules auto-label-width>
                <a-form-item field="name" label="标签名称">
                    <a-input
                        v-model.trim="form.name"
                        allow-clear
                        placeholder="请输入标签名称"
                    />
                </a-form-item>

                <a-form-item field="slug" label="标签标识">
                    <a-input
                        v-model="form.slug"
                        allow-clear
                        placeholder="请输入标签标识"
                    />
                </a-form-item>

                <a-form-item field="color" label="标签颜色">
                    <a-color-picker
                        v-model="form.color"
                        allow-clear
                        placeholder="请选择标签颜色"
                        showPreset
                        showText
                    />
                </a-form-item>
            </a-form>
        </a-spin>
    </a-drawer>
</template>

<style scoped>

</style>
